package com.ruoyi.fun.controller;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpEntity;
import org.springframework.http.MediaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.fun.domain.EcLogistics;
import com.ruoyi.fun.domain.EcOrder;
import com.ruoyi.fun.domain.EcOrderItem;
import com.ruoyi.fun.domain.SysWechatConfig;
import com.ruoyi.fun.service.IEcLogisticsService;
import com.ruoyi.fun.service.IEcOrderService;
import com.ruoyi.fun.service.IEcOrderItemService;
import com.ruoyi.fun.service.ISysWechatConfigService;
import com.ruoyi.system.domain.SysUserWechat;
import com.ruoyi.system.service.ISysUserWechatService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 物流信息Controller
 * 
 * @author ruoyi
 * @date 2025-08-06
 */
@RestController
@RequestMapping("/fun/logistics")
public class EcLogisticsController extends BaseController
{
    @Autowired
    private IEcLogisticsService ecLogisticsService;
    
    @Autowired
    private IEcOrderService ecOrderService;
    
    @Autowired
    private IEcOrderItemService ecOrderItemService;
    
    @Autowired
    private ISysWechatConfigService sysWechatConfigService;
    
    @Autowired
    private ISysUserWechatService sysUserWechatService;

    /**
     * 查询物流信息列表
     */
    @PreAuthorize("@ss.hasPermi('fun:logistics:list')")
    @GetMapping("/list")
    public TableDataInfo list(EcLogistics ecLogistics)
    {
        startPage();
        List<EcLogistics> list = ecLogisticsService.selectEcLogisticsList(ecLogistics);
        return getDataTable(list);
    }

    /**
     * 导出物流信息列表
     */
    @PreAuthorize("@ss.hasPermi('fun:logistics:export')")
    @Log(title = "物流信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, EcLogistics ecLogistics)
    {
        List<EcLogistics> list = ecLogisticsService.selectEcLogisticsList(ecLogistics);
        ExcelUtil<EcLogistics> util = new ExcelUtil<EcLogistics>(EcLogistics.class);
        util.exportExcel(response, list, "物流信息数据");
    }

    /**
     * 获取物流详细信息
     */
    @PreAuthorize("@ss.hasPermi('fun:logistics:query')")
    @GetMapping(value = "/{logisticsId}")
    public AjaxResult getInfo(@PathVariable("logisticsId") Long logisticsId)
    {
        Long orgId = getOrgId();
        // 103组织拥有不过滤的权限
        if (orgId != null && orgId == 103L) {
            orgId = null;
        }
        return success(ecLogisticsService.selectEcLogisticsByLogisticsIdAndOrgId(logisticsId, orgId));
    }

    /**
     * 新增物流信息
     */
    @PreAuthorize("@ss.hasPermi('fun:logistics:add')")
    @Log(title = "物流信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody EcLogistics ecLogistics)
    {
        ecLogistics.setOrgId(getOrgId());
        return toAjax(ecLogisticsService.insertEcLogistics(ecLogistics));
    }

    /**
     * 修改物流信息
     */
    @PreAuthorize("@ss.hasPermi('fun:logistics:edit')")
    @Log(title = "物流信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody EcLogistics ecLogistics)
    {
        return toAjax(ecLogisticsService.updateEcLogistics(ecLogistics));
    }

    /**
     * 删除物流信息
     */
    @PreAuthorize("@ss.hasPermi('fun:logistics:remove')")
    @Log(title = "物流信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{logisticsIds}")
    public AjaxResult remove(@PathVariable Long[] logisticsIds)
    {
        return toAjax(ecLogisticsService.deleteEcLogisticsByLogisticsIds(logisticsIds));
    }

    /**
     * 查询订单发货状态接口
     */
    /**
     * 查询订单发货状态
     */
    @PostMapping("/queryShippingStatus")
    public AjaxResult queryShippingStatus(@RequestBody Map<String, Object> params) {
        try {
            System.out.println("=== 查询订单发货状态接口开始 ===");
            System.out.println("接收到的参数: " + params);
            
            // 解析参数
            String orderNo = params.get("orderNo").toString();
            
            // 查询订单信息 - 通过订单号查询
            EcOrder queryOrder = new EcOrder();
            queryOrder.setOrderNo(orderNo);
            List<EcOrder> orderList = ecOrderService.selectEcOrderList(queryOrder);
            if (orderList == null || orderList.isEmpty()) {
                return AjaxResult.error("订单不存在");
            }
            EcOrder order = orderList.get(0);
            
            // 查询用户微信信息
            SysUserWechat userWechat = sysUserWechatService.selectSysUserWechatByUserId(order.getUserId());
            if (userWechat == null) {
                return AjaxResult.error("用户微信信息不存在");
            }
            
            // 查询微信配置
            List<SysWechatConfig> wechatConfigs = sysWechatConfigService.selectSysWechatConfigByOrgId(String.valueOf(order.getOrgId()));
            if (wechatConfigs == null || wechatConfigs.isEmpty()) {
                return AjaxResult.error("微信配置不存在");
            }
            SysWechatConfig wechatConfig = wechatConfigs.get(0);
            
            // 获取微信access_token
            String accessToken = getWechatAccessToken(wechatConfig.getWechatAppid(), wechatConfig.getWechatAppsecret());
            if (accessToken == null) {
                return AjaxResult.error("获取微信access_token失败");
            }
            
            // 调用微信查询发货状态API
            Map<String, Object> result = queryWechatShippingStatus(accessToken, order, wechatConfig);
            
            return AjaxResult.success("查询成功", result);
            
        } catch (Exception e) {
            System.out.println("查询订单发货状态异常: " + e.getMessage());
            e.printStackTrace();
            return AjaxResult.error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 微信发货接口
     */
    @PostMapping("/wechatShipping")
    public AjaxResult wechatShipping(@RequestBody Map<String, Object> params) {
        try {
            System.out.println("=== 微信发货接口开始 ===");
            System.out.println("接收到的参数: " + params);
            
            // 解析参数
            Long orderId = Long.valueOf(params.get("orderId").toString());
            
            // 新增物流类型参数
            Integer logisticsType = params.get("logistics_type") != null ? 
                Integer.valueOf(params.get("logistics_type").toString()) : 1;
            
            // 物流信息（仅快递配送时需要）
            String trackingNo = "";
            String receiverContact = "";
            
            if (logisticsType == 1) { // 快递配送
                // 从shipping_list中获取tracking_no
                if (params.get("shipping_list") != null) {
                    List<Map<String, Object>> shippingList = (List<Map<String, Object>>) params.get("shipping_list");
                    if (!shippingList.isEmpty()) {
                        trackingNo = shippingList.get(0).get("tracking_no") != null ? 
                            shippingList.get(0).get("tracking_no").toString() : "";
                    }
                }
                
                // 从contact中获取receiver_contact
                if (params.get("contact") != null) {
                    Map<String, Object> contact = (Map<String, Object>) params.get("contact");
                    receiverContact = contact.get("receiver_contact") != null ? 
                        contact.get("receiver_contact").toString() : "";
                }
            }
            
            System.out.println("订单ID: " + orderId);
            System.out.println("物流类型: " + logisticsType);
            System.out.println("物流单号: " + trackingNo);
            System.out.println("收货联系方式: " + receiverContact);
            
            // 1. 查询订单信息
            EcOrder order = ecOrderService.selectEcOrderByOrderId(orderId);
            if (order == null) {
                System.out.println("订单不存在: " + orderId);
                return AjaxResult.error("订单不存在");
            }
            System.out.println("查询到订单信息: " + order.toString());
            
            // 2. 根据用户ID查询用户微信信息
            SysUserWechat userWechat = sysUserWechatService.selectSysUserWechatByUserId(order.getUserId());
            if (userWechat == null) {
                System.out.println("用户未绑定微信: " + order.getUserId());
                return AjaxResult.error("用户未绑定微信");
            }
            System.out.println("查询到用户微信信息: " + userWechat.toString());
            
            // 3. 根据组织ID查询微信配置
            String orgId = userWechat.getSelectedOrg() != null ? userWechat.getSelectedOrg().toString() : "114";
            List<SysWechatConfig> wechatConfigs = sysWechatConfigService.selectSysWechatConfigByOrgId(orgId);
            if (wechatConfigs == null || wechatConfigs.isEmpty()) {
                System.out.println("未找到微信配置，组织ID: " + orgId);
                return AjaxResult.error("未找到微信配置");
            }
            SysWechatConfig wechatConfig = wechatConfigs.get(0);
            System.out.println("查询到微信配置: " + wechatConfig.toString());
            
            // 4. 获取微信access_token
            String accessToken = getWechatAccessToken(wechatConfig.getWechatAppid(), wechatConfig.getWechatAppsecret());
            if (accessToken == null) {
                System.out.println("获取access_token失败");
                return AjaxResult.error("获取微信access_token失败");
            }
            System.out.println("获取到access_token: " + accessToken);
            
            // 5. 调用微信发货接口
            boolean result = callWechatShippingApi(accessToken, order, userWechat, wechatConfig, 
                logisticsType, trackingNo, receiverContact);
            
            if (result) {
                System.out.println("微信发货接口调用成功");
                return AjaxResult.success("微信发货成功");
            } else {
                System.out.println("微信发货接口调用失败");
                return AjaxResult.error("微信发货失败");
            }
            
        } catch (Exception e) {
            System.out.println("微信发货接口异常: " + e.getMessage());
            e.printStackTrace();
            return AjaxResult.error("微信发货异常: " + e.getMessage());
        }
    }
    
    /**
     * 根据订单号构建商品描述
     * 格式：商品名*数量，用逗号分隔
     */
    private String buildItemDescription(String orderNo) {
        try {
            System.out.println("=== 构建商品描述 ===");
            System.out.println("订单号: " + orderNo);
            
            // 根据订单号查询订单商品
            EcOrderItem queryItem = new EcOrderItem();
            queryItem.setOrderNo(orderNo);
            List<EcOrderItem> itemList = ecOrderItemService.selectEcOrderItemList(queryItem);
            
            System.out.println("查询到订单商品数量: " + (itemList != null ? itemList.size() : 0));
            
            if (itemList == null || itemList.isEmpty()) {
                System.out.println("未找到订单商品，使用默认描述");
                return "订单商品";
            }
            
            // 构建商品描述字符串
            StringBuilder itemDesc = new StringBuilder();
            for (int i = 0; i < itemList.size(); i++) {
                EcOrderItem item = itemList.get(i);
                String productName = item.getProductName();
                Long quantity = item.getProductQuantity();
                
                System.out.println("商品" + (i + 1) + ": " + productName + " x " + quantity);
                
                if (productName != null && quantity != null) {
                    itemDesc.append(productName).append("*").append(quantity);
                    if (i < itemList.size() - 1) {
                        itemDesc.append(",");
                    }
                }
            }
            
            String result = itemDesc.toString();
            System.out.println("构建的商品描述: " + result);
            
            return result.isEmpty() ? "订单商品" : result;
            
        } catch (Exception e) {
            System.out.println("构建商品描述时发生异常: " + e.getMessage());
            e.printStackTrace();
            return "订单商品";
        }
    }
    
    /**
     * 获取微信access_token
     */
    private String getWechatAccessToken(String appid, String secret) {
        try {
            System.out.println("=== 获取微信access_token ===");
            System.out.println("appid: " + appid);
            System.out.println("secret: " + secret);
            
            String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
            
            RestTemplate restTemplate = new RestTemplate();
            String response = restTemplate.getForObject(url, String.class);
            System.out.println("微信access_token响应: " + response);
            
            ObjectMapper mapper = new ObjectMapper();
            JsonNode jsonNode = mapper.readTree(response);
            
            if (jsonNode.has("access_token")) {
                String accessToken = jsonNode.get("access_token").asText();
                System.out.println("成功获取access_token: " + accessToken);
                return accessToken;
            } else {
                System.out.println("获取access_token失败: " + response);
                return null;
            }
        } catch (Exception e) {
            System.out.println("获取access_token异常: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }
    
    /**
     * 调用微信发货API
     */
    private boolean callWechatShippingApi(String accessToken, EcOrder order, SysUserWechat userWechat, 
                                         SysWechatConfig wechatConfig, Integer logisticsType, String trackingNo, String receiverContact) {
        try {
            System.out.println("=== 调用微信发货API ===");
            System.out.println("订单信息: " + order.toString());
            System.out.println("用户微信信息: " + userWechat.toString());
            System.out.println("微信配置信息: " + wechatConfig.toString());
            System.out.println("物流类型: " + logisticsType);
            System.out.println("物流单号: " + trackingNo);
            System.out.println("收货联系方式: " + receiverContact);
            
            String url = "https://api.weixin.qq.com/wxa/sec/order/upload_shipping_info?access_token=" + accessToken;
            System.out.println("请求URL: " + url);
            
            // 构建请求参数 - 根据微信官方文档格式
            Map<String, Object> requestData = new HashMap<>();
            
            // order_key参数 - 必填
            Map<String, Object> orderKey = new HashMap<>();
            // 使用商户侧单号形式
            orderKey.put("order_number_type", 1); // 1-商户侧单号形式
            orderKey.put("mchid", wechatConfig.getMchId()); // 微信商户号
            orderKey.put("out_trade_no", order.getOrderNo()); // 商户系统内部订单号
            requestData.put("order_key", orderKey);
            
            // 详细打印order_key参数用于调试
            System.out.println("=== order_key参数详情 ===");
            System.out.println("order_number_type: " + orderKey.get("order_number_type"));
            System.out.println("mchid: " + orderKey.get("mchid"));
            System.out.println("out_trade_no: " + orderKey.get("out_trade_no"));
            System.out.println("订单号: " + order.getOrderNo());
            System.out.println("订单支付状态: " + order.getPaymentStatus());
            System.out.println("订单状态: " + order.getOrderStatus());
            System.out.println("订单支付时间: " + order.getPaymentTime());
            
            // logistics_type - 必填，物流模式
            // 1-实体物流配送 2-同城配送 3-虚拟商品 4-用户自提
            requestData.put("logistics_type", logisticsType);
            
            // delivery_mode - 必填，发货模式
            requestData.put("delivery_mode", 1); // 1-统一发货
            
            // shipping_list - 必填，物流信息列表
            List<Map<String, Object>> shippingList = new ArrayList<>();
            Map<String, Object> shipping = new HashMap<>();
            
            // 根据logistics_type决定是否需要物流信息
            if (logisticsType == 1) {
                // 实体物流配送时，tracking_no为必填
                if (trackingNo == null || trackingNo.trim().isEmpty()) {
                    System.out.println("实体物流配送时物流单号不能为空");
                    return false;
                }
                shipping.put("tracking_no", trackingNo.trim());
                
                // 添加收货联系方式
                if (receiverContact != null && !receiverContact.trim().isEmpty()) {
                    shipping.put("receiver_contact", receiverContact.trim());
                }
            }
            
            // item_desc - 必填，商品信息描述
            // 根据订单号查询订单商品，构建商品描述
            String itemDesc = buildItemDescription(order.getOrderNo());
            shipping.put("item_desc", itemDesc);
            
            shippingList.add(shipping);
            requestData.put("shipping_list", shippingList);
            
            // upload_time - 必填，RFC 3339格式时间戳
            java.time.ZonedDateTime now = java.time.ZonedDateTime.now(java.time.ZoneId.of("Asia/Shanghai"));
            String uploadTime = now.format(java.time.format.DateTimeFormatter.ISO_OFFSET_DATE_TIME);
            requestData.put("upload_time", uploadTime);
            
            // payer - 必填，支付者信息
            Map<String, Object> payer = new HashMap<>();
            if (userWechat != null && userWechat.getOpenId() != null && !userWechat.getOpenId().trim().isEmpty()) {
                payer.put("openid", userWechat.getOpenId().trim());
            } else {
                System.out.println("警告: 用户openid为空，这可能导致接口调用失败");
                payer.put("openid", ""); // 设置空值，让微信返回具体错误
            }
            requestData.put("payer", payer);
            
            // 打印关键参数用于调试
            System.out.println("upload_time: " + requestData.get("upload_time"));
            System.out.println("payer: " + requestData.get("payer"));
            System.out.println("logistics_type: " + requestData.get("logistics_type"));
            System.out.println("delivery_mode: " + requestData.get("delivery_mode"));
            System.out.println("order_key: " + requestData.get("order_key"));
            System.out.println("shipping_list size: " + ((List<?>) requestData.get("shipping_list")).size());
            
            System.out.println("=== 微信发货API请求参数详情 ===");
            System.out.println("完整请求参数: " + requestData);
            System.out.println("order_key: " + requestData.get("order_key"));
            System.out.println("logistics_type: " + requestData.get("logistics_type"));
            System.out.println("delivery_mode: " + requestData.get("delivery_mode"));
            System.out.println("shipping_list: " + requestData.get("shipping_list"));
            System.out.println("upload_time: " + requestData.get("upload_time"));
            System.out.println("payer: " + requestData.get("payer"));
            
            // 发送请求
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("User-Agent", "Mozilla/5.0");
            
            ObjectMapper mapper = new ObjectMapper();
            String jsonData = mapper.writeValueAsString(requestData);
            System.out.println("=== 微信发货API请求JSON ===");
            System.out.println(jsonData);
            
            HttpEntity<String> entity = new HttpEntity<>(jsonData, headers);
            
            System.out.println("=== 开始发送HTTP请求 ===");
            String response = restTemplate.postForObject(url, entity, String.class);
            System.out.println("=== 微信发货API原始响应 ===");
            System.out.println("响应内容: " + response);
            
            // 解析响应
            if (response == null || response.trim().isEmpty()) {
                System.out.println("微信API返回空响应");
                return false;
            }
            
            JsonNode jsonNode = mapper.readTree(response);
            System.out.println("=== 解析后的响应JSON ===");
            System.out.println("JSON节点: " + jsonNode.toString());
            
            int errcode = jsonNode.has("errcode") ? jsonNode.get("errcode").asInt() : -1;
            String errmsg = jsonNode.has("errmsg") ? jsonNode.get("errmsg").asText() : "未知错误";
            
            System.out.println("错误码: " + errcode);
            System.out.println("错误信息: " + errmsg);
            
            if (errcode == 0) {
                System.out.println("=== 微信发货API调用成功 ===");
                return true;
            } else {
                System.out.println("=== 微信发货API调用失败 ===");
                System.out.println("错误码: " + errcode + ", 错误信息: " + errmsg);
                
                // 根据错误码提供具体的错误分析
                switch (errcode) {
                    case 47001:
                        System.out.println("错误分析: 数据格式错误，请检查请求参数格式是否符合微信官方文档要求");
                        break;
                    case 40013:
                        System.out.println("错误分析: 不合法的AppID，请检查微信配置");
                        break;
                    case 42001:
                        System.out.println("错误分析: access_token超时，请重新获取");
                        break;
                    case 40001:
                        System.out.println("错误分析: 获取access_token时AppSecret错误，或者access_token无效");
                        break;
                    case 10060001:
                        System.out.println("错误分析: 支付单不存在，可能原因：");
                        System.out.println("1. 商户号(mchid)与订单号(out_trade_no)不匹配");
                        System.out.println("2. 订单未支付成功或支付状态异常");
                        System.out.println("3. 订单信息同步延迟，建议等待10秒后重试");
                        System.out.println("4. 使用了开发工具扫码支付的订单（此类订单不会进入发货管理）");
                        System.out.println("5. 订单已经完成发货操作");
                        break;
                    default:
                        System.out.println("错误分析: 其他错误，请查看微信官方文档");
                        break;
                }
                return false;
            }
            
        } catch (Exception e) {
            System.out.println("=== 调用微信发货API发生异常 ===");
            System.out.println("异常类型: " + e.getClass().getSimpleName());
            System.out.println("异常信息: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 调用微信查询发货状态API
     */
    private Map<String, Object> queryWechatShippingStatus(String accessToken, EcOrder order, SysWechatConfig wechatConfig) {
        try {
            System.out.println("=== 查询微信发货状态 ===");
            System.out.println("订单信息: " + order.toString());
            System.out.println("微信配置信息: " + wechatConfig.toString());
            
            String url = "https://api.weixin.qq.com/wxa/sec/order/get_order?access_token=" + accessToken;
            System.out.println("请求URL: " + url);
            
            // 构建请求参数 - 根据微信官方文档，直接使用顶级参数
            Map<String, Object> requestData = new HashMap<>();
            
            // 根据微信官方文档，使用merchant_trade_no参数
            requestData.put("merchant_trade_no", order.getOrderNo()); // 商户系统内部订单号
            
            // 详细打印请求参数用于调试
            System.out.println("=== 请求参数详情 ===");
            System.out.println("merchant_trade_no: " + order.getOrderNo());
            System.out.println("订单号: " + order.getOrderNo());
            System.out.println("订单支付状态: " + order.getPaymentStatus());
            System.out.println("订单状态: " + order.getOrderStatus());
            System.out.println("订单支付时间: " + order.getPaymentTime());
            
            System.out.println("请求参数: " + requestData);
            
            // 发送HTTP请求
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            
            ObjectMapper mapper = new ObjectMapper();
            String jsonData = mapper.writeValueAsString(requestData);
            System.out.println("请求JSON: " + jsonData);
            
            HttpEntity<String> entity = new HttpEntity<>(jsonData, headers);
            String response = restTemplate.postForObject(url, entity, String.class);
            System.out.println("=== 微信查询发货状态API原始响应 ===");
            System.out.println("响应内容: " + response);
            
            // 解析响应
            if (response == null || response.trim().isEmpty()) {
                System.out.println("微信API返回空响应");
                Map<String, Object> errorResult = new HashMap<>();
                errorResult.put("success", false);
                errorResult.put("message", "微信API返回空响应");
                return errorResult;
            }
            
            JsonNode jsonNode = mapper.readTree(response);
            System.out.println("=== 解析后的响应JSON ===");
            System.out.println("JSON节点: " + jsonNode.toString());
            
            int errcode = jsonNode.has("errcode") ? jsonNode.get("errcode").asInt() : -1;
            String errmsg = jsonNode.has("errmsg") ? jsonNode.get("errmsg").asText() : "未知错误";
            
            System.out.println("错误码: " + errcode);
            System.out.println("错误信息: " + errmsg);
            
            Map<String, Object> result = new HashMap<>();
            
            if (errcode == 0) {
                System.out.println("=== 微信查询发货状态API调用成功 ===");
                result.put("success", true);
                result.put("message", "查询成功");
                
                // 解析订单状态信息
                if (jsonNode.has("order")) {
                    JsonNode orderNode = jsonNode.get("order");
                    int orderState = orderNode.has("order_state") ? orderNode.get("order_state").asInt() : 0;
                    
                    System.out.println("=== 订单状态分析 ===");
                    System.out.println("订单号: " + order.getOrderNo());
                    System.out.println("微信返回的order_state值: " + orderState);
                    System.out.println("order_state含义: " + getOrderStateDescription(orderState));
                    
                    result.put("order_state", orderState);
                    
                    // 检查是否已确认收货
                    // 根据微信文档，order_state: 1-待发货 2-已发货 3-确认收货 4-交易完成 5-已退款
                    boolean isConfirmed = orderState >= 3;
                    System.out.println("计算的isConfirmed值: " + isConfirmed);
                    result.put("isConfirmed", isConfirmed);
                    
                    if (orderNode.has("shipping_list")) {
                        result.put("shipping_list", orderNode.get("shipping_list"));
                    }
                }
                
            } else {
                System.out.println("=== 微信查询发货状态API调用失败 ===");
                System.out.println("错误码: " + errcode + ", 错误信息: " + errmsg);
                result.put("success", false);
                result.put("message", "查询失败: " + errmsg);
                result.put("errcode", errcode);
                result.put("errmsg", errmsg);
            }
            
            return result;
            
        } catch (Exception e) {
            System.out.println("调用微信查询发货状态API异常: " + e.getMessage());
            e.printStackTrace();
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("success", false);
            errorResult.put("message", "调用微信API异常: " + e.getMessage());
            return errorResult;
        }
    }

    /**
     * 查询订单列表
     */
    @PreAuthorize("@ss.hasPermi('fun:eclogistics:query')")
    @GetMapping(value = "/{logisticsId}/org/{orgId}")
    public AjaxResult getInfoByOrgId(@PathVariable("logisticsId") Long logisticsId, @PathVariable("orgId") Long orgId)
    {
        return success(ecLogisticsService.selectEcLogisticsByLogisticsIdAndOrgId(logisticsId, orgId));
    }

    /**
     * 根据组织ID查询列表
     */
    @PreAuthorize("@ss.hasPermi('fun:eclogistics:list')")
    @GetMapping("/org/{orgId}")
    public TableDataInfo listByOrgId(@PathVariable Long orgId)
    {
        startPage();
        EcLogistics ecLogistics = new EcLogistics();
        List<EcLogistics> list = ecLogisticsService.selectEcLogisticsListByOrgId(ecLogistics, orgId);
        return getDataTable(list);
    }

    /**
     * 获取订单状态描述
     */
    private String getOrderStateDescription(int orderState) {
        switch (orderState) {
            case 1:
                return "待发货";
            case 2:
                return "已发货";
            case 3:
                return "确认收货";
            case 4:
                return "交易完成";
            case 5:
                return "已退款";
            default:
                return "未知状态(" + orderState + ")";
        }
    }


}